﻿module Tww.Pixxler.ImageEffects

  open System
  open Tww.Pixxler.ColorTypes
  open Tww.Pixxler.BitmapUtils
  open System.Threading.Tasks


  // Vereinfachungsmethode
  let pfor nfrom nto f = 
       Parallel.For(nfrom, nto + 1, Action<_>(f)) |> ignore

  let blur(arr:SimpleColor[,], x, y) =
    // Überprüfen ob die Indizes passen
    let hgt, wid = arr.GetLength(0) - 1, arr.GetLength(1) - 1
    let checkW x = max 0 (min wid x)
    let checkH y = max 0 (min hgt y)
    // Sammeln von naheliegenden Pixeln
    seq { for dy in -2 .. 2 do
            for dx in -2 .. 2 do
              yield arr.[checkH(y + dy), checkW(x + dx)] }
    |> Seq.average // Durschnittsfarbe berechnen

  let runEffect isParallel effect (arr:SimpleColor[,]) =
    // Decide whether to use parallel or standard for
    let forLoop = 
      if isParallel then pfor 
      else (fun x y f -> 
        for i = x to y do f(i))

    // Create the resulting array
    let hgt, wid = arr.GetLength(0) - 1, arr.GetLength(1) - 1
    let res = Array2D.create (hgt + 1) (wid + 1) SimpleColor.Zero
    
    forLoop 0 hgt (fun y ->
      for x = 0 to wid do
        res.[y, x] <- effect(arr, x, y)
    )
    res

  let SequentialBlur(arr) = runEffect false blur arr
  let ParallelBlur(arr) = runEffect true blur arr

